package com.lv.common.utils;

/**
 * 作者： ygx
 * 创建日期：2022/5/30 6:17 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * _              _           _     _   ____  _             _ _
 * / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * /_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 */

import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.net.Uri;
import android.util.Log;

import androidx.annotation.UiThread;

import com.blankj.utilcode.util.ToastUtils;
import com.lv.common.widget.camera.OverLayerTopView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Bitmap util.
 * <p>从Uri直接读取图片流，避免路径转换的适配问题</p>
 */
public class BitmapUtil {
    /**
     * 读取一个缩放后的图片，限定图片大小，避免OOM
     *
     * @param uri       图片uri，支持“file://”、“content://”
     * @param maxWidth  最大允许宽度
     * @param maxHeight 最大允许高度
     * @return 返回一个缩放后的Bitmap，失败则返回null
     */
    public static Bitmap decodeUri(Context context, Uri uri, int maxWidth, int maxHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; //只读取图片尺寸
        readBitmapScale(context, uri, options);

        //计算实际缩放比例
        int scale = 1;
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            if ((options.outWidth / scale > maxWidth &&
                    options.outWidth / scale > maxWidth * 1.4) ||
                    (options.outHeight / scale > maxHeight &&
                            options.outHeight / scale > maxHeight * 1.4)) {
                scale++;
            } else {
                break;
            }
        }

        options.inSampleSize = scale;
        options.inJustDecodeBounds = false;//读取图片内容
        options.inPreferredConfig = Bitmap.Config.RGB_565; //根据情况进行修改
        Bitmap bitmap = null;
        try {
            bitmap = readBitmapData(context, uri, options);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    private static void readBitmapScale(Context context, Uri uri, BitmapFactory.Options options) {
        if (uri == null) {
            return;
        }
        String scheme = uri.getScheme();
        if (ContentResolver.SCHEME_CONTENT.equals(scheme) ||
                ContentResolver.SCHEME_FILE.equals(scheme)) {
            InputStream stream = null;
            try {
                stream = context.getContentResolver().openInputStream(uri);
                BitmapFactory.decodeStream(stream, null, options);
            } catch (Exception e) {
                Log.w("readBitmapScale", "Unable to open content: " + uri, e);
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException e) {
                        Log.e("readBitmapScale", "Unable to close content: " + uri, e);
                    }
                }
            }
        } else if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
            Log.e("readBitmapScale", "Unable to close content: " + uri);
        } else {
            Log.e("readBitmapScale", "Unable to close content: " + uri);
        }
    }

    private static Bitmap readBitmapData(Context context, Uri uri, BitmapFactory.Options options) {
        if (uri == null) {
            return null;
        }
        Bitmap bitmap = null;
        String scheme = uri.getScheme();
        if (ContentResolver.SCHEME_CONTENT.equals(scheme) ||
                ContentResolver.SCHEME_FILE.equals(scheme)) {
            InputStream stream = null;
            try {
                stream = context.getContentResolver().openInputStream(uri);
                bitmap = BitmapFactory.decodeStream(stream, null, options);
            } catch (Exception e) {
                Log.e("readBitmapData", "Unable to open content: " + uri, e);
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException e) {
                        Log.e("readBitmapData", "Unable to close content: " + uri, e);
                    }
                }
            }
        } else if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
            Log.e("readBitmapData", "Unable to close content: " + uri);
        } else {
            Log.e("readBitmapData", "Unable to close content: " + uri);
        }
        return bitmap;
    }

    public static final int IMAGE_SIZE = 32768;//微信分享图片大小限制32k限制

    public static byte[] getImageBytes(String path) {
        try {
            URL url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setReadTimeout(6 * 1000);
            InputStream inputStream = null;
            Bitmap bmp = null;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = httpURLConnection.getInputStream();
                bmp = BitmapFactory.decodeStream(httpURLConnection.getInputStream());
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
            }
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            int options = 100;
            Log.e("TAG", "getImageBytes length: " + outputStream.toByteArray().length);
            while (outputStream.toByteArray().length > IMAGE_SIZE && options != 10) {
                outputStream.reset(); //清空baos
                bmp.compress(Bitmap.CompressFormat.JPEG, options, outputStream);//这里压缩options%，把压缩后的数据存放到baos中
                options -= 10;
            }

            bmp.recycle();//回收bmp
            outputStream.close();
            inputStream.close();

            if (options == 100) {
                Log.e("TAG", "getImageBytes未压缩: ");
                Log.e("TAG", "getImageBytes length: " + outputStream.toByteArray().length);
                return outputStream.toByteArray();
            } else {
                Log.e("TAG", "getImageBytes 压缩: ");
                Log.e("TAG", "getImageBytes length: " + outputStream.toByteArray().length);

                return outputStream.toByteArray();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Bitmap getImageBitmap(String path) {
        try {
            URL url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setReadTimeout(6 * 1000);
            InputStream inputStream = null;
            Bitmap bmp = null;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = httpURLConnection.getInputStream();
                bmp = BitmapFactory.decodeStream(httpURLConnection.getInputStream());
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
            }
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            int options = 100;
            Log.e("TAG", "getImageBytes length: " + outputStream.toByteArray().length);
            while (outputStream.toByteArray().length > IMAGE_SIZE && options != 10) {
                outputStream.reset(); //清空baos
                bmp.compress(Bitmap.CompressFormat.JPEG, options, outputStream);//这里压缩options%，把压缩后的数据存放到baos中
                options -= 10;
            }

            return bmp;
//            bmp.recycle();//回收bmp
//            outputStream.close();
//            inputStream.close();
//
//            if (options == 100) {
//                Log.e("TAG", "getImageBytes未压缩: ");
//                Log.e("TAG", "getImageBytes length: " + outputStream.toByteArray().length);
//                return outputStream.toByteArray();
//            } else {
//                Log.e("TAG", "getImageBytes 压缩: ");
//                Log.e("TAG", "getImageBytes length: " + outputStream.toByteArray().length);
//
//                return outputStream.toByteArray();
//            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Bitmap转换成byte[]并且进行压缩,压缩到不大于maxkb
     *
     * @param bitmap
     * @param maxkb
     * @return
     */
    public static byte[] bitmap2Bytes(Bitmap bitmap, int maxkb) {
        try {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 50, output);
            int options = 100;
            while (output.toByteArray().length > maxkb && options != 10) {
                output.reset(); //清空output
                bitmap.compress(Bitmap.CompressFormat.PNG, options, output);//这里压缩options%，把压缩后的数据存放到output中
                options -= 10;
            }
            return output.toByteArray();
        } catch (Exception e) {
            return new byte[0];
        }
    }

    /**
     * Bitmap转换成byte[]并且进行压缩,压缩到不大于maxkb
     *
     * @param bitmap
     * @return
     */
    public static byte[] bitmap2Bytes(Bitmap bitmap) {
        try {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, output);
//        int options = 100;
//        while (output.toByteArray().length > maxkb && options != 10) {
//            output.reset(); //清空output
//            bitmap.compress(Bitmap.CompressFormat.PNG, options, output);//这里压缩options%，把压缩后的数据存放到output中
//            options -= 10;
//        }
            return output.toByteArray();
        } catch (Exception e) {
            return new byte[0];
        }
    }

    public static Bitmap getRectBitmap(Bitmap bitmap, OverLayerTopView mOverLayerView, int w, int h) {
        Rect centerRect = mOverLayerView.getCenterRect();
        int width = centerRect.right - centerRect.left;
        int height = centerRect.bottom - centerRect.top;
//        Bitmap scaleBitmap = scaleBitmap(bitmap, x, y);
        Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, w, h, false);
//        Bitmap rectBitmap = Bitmap.createBitmap(scaleBitmap, centerRect.left, centerRect.top, width, height);
        Bitmap rectBitmap = Bitmap.createBitmap(scaleBitmap, centerRect.left, (h - height) / 2, width, height);
//        Bitmap rectBitmap=Bitmap.createBitmap(bitmap,mOverLayerView.getLeft(),mCenterRect.top,width,height);

        return rectBitmap;
    }

    /**
     * 回收图片资源
     *
     * @param bitmap 图片资源
     */
    public static void recycleBitmap(Bitmap bitmap) {
        if (!bitmap.isRecycled()) {
            bitmap.recycle();
        }
    }
}


